/**
 * 
 */
package com.study.singleton;

import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;

import org.springframework.core.task.support.ExecutorServiceAdapter;

/**
 * 
 * 实现单例模式有4个步骤： 1) 静态私有属性 2) 私有构造方法 3) 公有的静态的获取实例的方法 4) 公有的业务方法
 * 
 * @author Administrator
 * @date 2019年6月24日
 */
// 懒汉式（线程不安全）
public class SingletonV2 {

	private static SingletonV2 instance;
	private Person person;

	private SingletonV2() {
		person = new Person("xiaoming");
	};

	public static SingletonV2 getInstance() {

		if (instance == null) {  //可能多个线程执行了这步
			try {
				Thread.sleep(2000);
			} catch (Exception e) {
			}
			instance = new SingletonV2();
		}
		return instance;
	}

	// 4、公有业务方法
	public String getPersonName() {
		return person.getName();
	}

	class Person {
		private String name;

		public Person(String n) {
			this.name = n;
		}

		public String getName() {
			return name;
		}
	}

	public static void main(String[] args) {
		
//		SingletonV2 v1 = SingletonV2.getInstance();
//		SingletonV2 v2 = SingletonV2.getInstance();
//		System.out.println(v1 == v2);
		ExecutorService newCachedThreadPool = Executors.newCachedThreadPool();
		for(int i =0; i < 5; i++){			
			newCachedThreadPool.execute( new Runnable(){
				
				@Override
				public void run() {
					SingletonV2 instance2 = SingletonV2.getInstance(); 
					System.out.println(Thread.currentThread().getName() + instance2);
				}
				
			});
		}
		System.out.println(SingletonV2.getInstance().getPersonName());
	}
}
